package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.asm.Advice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

import static com.sky.utils.WeChatPayUtil.WX_LOGIN;


@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatProperties weChatProperties;

    /**
     * 封装获取openID方法
     * @param code
     * @return
     */
    public String getOpenId(String code){
        //1.通过HttpClientUtil,构造请求和请求参数
        Map paramMap = new HashMap();
        paramMap.put("appId",weChatProperties.getAppid());
        paramMap.put("secret",weChatProperties.getSecret());
        paramMap.put("js_code",code);
        paramMap.put("secret",weChatProperties.getSecret());
        //2.发送请求到微信平台
        String entity = HttpClientUtil.doGet(WX_LOGIN, paramMap);

        //3.解析响应结果，后去到openid
        JSONObject jsonObject = JSON.parseObject(entity);
        String openid = jsonObject.getString("openid");
        log.info("微信用户的openid为：{}",openid);
        return openid;
    }

    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        String code = userLoginDTO.getCode();
        log.info("前端的传过来的code为：{}",code);
        String openId = getOpenId(code);
        //如果是新用户需要完成注册
        //判断是否是新用户（根据openid查询user表）
        User user = userMapper.getByOpenid(openId);
        if (user == null){
            user = User.builder()
                    .openid(openId)
                    .createTime(LocalDateTime.now())
                    .name("u_"+openId.substring(4,8))
                    .build();
            userMapper.insert(user);
        }

        //5.否则直接返回用户对象
        return user;
    }
}
